<?php

namespace app\api\controller\v1;

use app\api\model\Address as AddressModel;
use app\api\model\Area as AreaModel;
use app\api\validate\AddressValidate;
use app\common\controller\BaseController;
use think\Db;

/**
 * 地址
 */
class Address extends BaseController
{
    protected $noNeedLogin = ['area', 'city'];

   /**
    * 省市区
    */
   public function area()
   {
        $areas = AreaModel::getAreas();
        $areas ? $this->success('', compact('areas')) : $this->errorMsg(11000);
   }

   /**
    * 获取城市
    */
   public function city()
   {
       $city = AreaModel::getCity();
       $city ? $this->success('', $city) : $this->errorMsg(11000);
   }

   /**
    * 添加用户地址
    */
   public function create(AddressModel $addressModel, AddressValidate $addressValidate)
   {
        $this->isPost();
        $data = $this->request->post();
        $this->paramValidate($addressValidate, $data);
        $data['user_id'] = $this->userId;
        Db::startTrans();
       try {
           if (isset($data['is_default']) && $data['is_default']) {
               AddressModel::updateNotDefault($this->userId);
           }
           $addressModel->add($data);
           Db::commit();
       } catch (\Exception $e) {
           Db::rollback();
       }
       isset($e) ? $this->forbidden($e->getMessage()) : $this->success();
   }

    /**
     * 用户地址
     */
    public function index()
    {
        $address = AddressModel::getByUserId($this->userId);
        $address ? $this->success('', compact('address')) : $this->notFoundData();
    }

    /**
     * 用户地址详情
     */
    public function read()
    {
        $address = $this->detail();
        $this->success('', compact('address'));
    }

    /**
     * 编辑用户地址
     */
    public function update(AddressValidate $addressValidate)
    {
        $this->isPost();
        $data = $this->request->post();
        $this->paramValidate($addressValidate, $data);
        $address = $this->detail();
        Db::startTrans();
        try {
            if (isset($data['is_default']) && $data['is_default']) {
                AddressModel::updateNotDefault($this->userId);
            }
            $address->allowField(true)->save($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->forbidden() : $this->success();
    }

    /**
     * 删除地址
     */
    public function delete()
    {
        $address = $this->detail();
        $res = $address->delete();
        $res ? $this->success() : $this->forbidden();
    }

    /**
     * 获取地址信息
     */
    private function detail()
    {
        $addressId = $this->notEmpty('address_id');
        $address = AddressModel::with(['province', 'city', 'area'])->find($addressId);
        if (!$address) {
            $this->errorMsg(11001);
        }
        return $address;
    }
}
